import React, {
  Component,
  useState,
  useEffect
} from "react";
import {
  FlatList,
  View,
  Text,
  Image
} from "react-native";
import Content from "../../components/content/content";
import TaskProcessComponent from "../../components/task-process/task-process";
import TaskSimpleComponent from "../../components/task-simple/task-simple";
import TaskTimeComponent from "../../components/task-time/task-time";
import FooterLoading from "../../components/footer-loading/footer-loading";
import styles from "./process-task-sheet";

import * as api from "../../api";
import * as config from "../../config";
import {
  formatTaskData,
  concatTaskData
} from "../../baseData";

export default function ProcessTask(props) {
  const [data, setData] = useState([]);
  const [refresh, setRefresh] = useState(false);
  const [page, setPage] = useState(1);
  const [allPage, setAllPage] = useState(1);
  const [showEmpty, setShowEmpty] = useState(false);
  const [footerText, setFooterText] = useState(false);
  const type = props.type;

  const getTask = (data = []) => {
    setRefresh(true);
    api.getProcessTasks({
      page,
      page_size: config.PAGE_SIZE,
      type,
    }).then(res => {
      const allPage = Math.ceil(res.pagination.count / config.PAGE_SIZE);
      const result = type === 1 ? [...data, ...res.tasks] : concatTaskData(data, formatTaskData(res.tasks));
      setData(result);
      setAllPage(allPage);
      setEmptyComponent(result);
      setFooter(allPage);
    }).catch(rej => {
      global.showToast(rej);
    }).finally(() => {
      setRefresh(false);
    });
  }

  useEffect(() => {
    if (type === 1 || type === 3) {
      function handle() {
        setPage(0);
        setTimeout(() => {
          setPage(1);
        });
      }
      const fire = type === 1 ? 'applyTask' : 'checkTask';
      global.onfire.on(fire, handle);

      return () => {
        global.onfire.off(fire);
      }
    }
  }, []);

  useEffect(() => {
    if (page === 0) {
      return;
    }
    if (page === 1) {
      getTask();
    } else {
      getTask(data);
    }
  }, [page]);

  setEmptyComponent = (result) => {
    setShowEmpty(result.length > 0 ? false : true);
  };

  setFooter = (result) => {
    setFooterText(page >= result);
  };

  onEndReached = (e) => {
    if (data.length < config.PAGE_SIZE) {
      return;
    }

    if (page >= allPage) {
      return;
    }

    setPage(page + 1);
  }

  onRefresh = () => {
    setPage(0);
    setTimeout(() => {
      setPage(1);
    });
  }

  renderData = ({
    item,
    index
  }) => {
    if (type === 1) {
      return (
        <TaskProcessComponent key={item.applicant_id} { ...item } router='AchieveTask' />
      )
    }
    return (
      <View style={{width:'100%'}}>
        <TaskTimeComponent key={index} time={item.time} count={item.count} />
        {
          item.data.map((v) => {
            return (
              <TaskSimpleComponent key={v.applicant_id} {...v} router={props.router} />
            );
          })
        }
      </View>
    );
  };

  footer = () => {
    if (page <= 1) {
      return;
    }
    return <FooterLoading showLoading={footerText} />
  };

  Empty = () => {
    return (
      showEmpty ? <Text style={{textAlign: "center",marginTop:50}}>暂无数据</Text> : null
    );
  };

  return (
    <Content>
      <View style={styles.content}>
        <FlatList 
          style={styles.listContent}
          data={data}
          renderItem={this.renderData}
          refreshing={refresh}
          onRefresh={this.onRefresh}
          onEndReachedThreshold={.3}
          onEndReached={this.onEndReached}
          scrollEventThrottle={500}
          ListEmptyComponent={this.Empty()}
          ListFooterComponent={this.footer()}
          keyExtractor={(item,index)=>index.toString()}
          progressViewOffset={20}
        />
      </View>
    </Content>
  )
}